package com.xin.di.uav.applet.service.impl;

import com.xin.di.uav.mapper.SpecificationDao;
import com.xin.di.uav.po.SpecificationPO;
import com.xin.di.uav.applet.request.AddSpecificationRequest;
import com.xin.di.uav.applet.resp.SpecificationResponse;
import com.xin.di.uav.applet.service.SpecificationService;
import com.xin.di.uav.common.utils.BeanUtil;
import com.xin.di.uav.common.utils.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpecificationServiceImpl implements SpecificationService {
    @Autowired
    private SpecificationDao specificationDao;

    @Override
    public SpecificationResponse getList(Integer page, Integer size, String productId) {
        SpecificationResponse specificationResponse = new SpecificationResponse();
        List<SpecificationResponse.Record> recordList = new ArrayList<>();
        Integer total = specificationDao.countListByProductId(productId);
        if (total > 0) {
            page = (page - 1) * size;
            List<SpecificationPO> specificationPOS = specificationDao.selListByProductId(productId, page, size);
            for (SpecificationPO specificationPO : specificationPOS) {
                SpecificationResponse.Record record = BeanUtil.copyProperties(specificationPO, SpecificationResponse.Record.class);
                recordList.add(record);
            }
            specificationResponse.setRecordList(recordList);
        }

        return specificationResponse;
    }

    @Override
    public void save(AddSpecificationRequest addSpecificationRequest) {
        specificationDao.deleteByProductId(addSpecificationRequest.getProductId());
        List<AddSpecificationRequest.Record> recordList = addSpecificationRequest.getRecordList();
        for (AddSpecificationRequest.Record record : recordList) {
            SpecificationPO specificationPO = BeanUtil.copyProperties(record, SpecificationPO.class);
            specificationPO.setId(IdUtils.getId());
            specificationPO.setProductId(addSpecificationRequest.getProductId());
            specificationDao.insert(specificationPO);
        }
    }
}
